package xian.woniu.config.globalFilter;


import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import xian.woniu.service.IUserService;
import xian.woniu.util.ResultVO;



@Component
public class AuthGlobalFilter implements GlobalFilter,Ordered {


    private IUserService iUserService;

    public AuthGlobalFilter(IUserService iUserService){
        this.iUserService=iUserService;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 如果发现请求的地址是Login，就直接放行
      String uri=exchange.getRequest().getURI().toString();

        if (uri.contains("login")||uri.contains("regist")||uri.contains("save")) {
            return chain.filter(exchange);
        }

        //如果没有访问登录就看他带没有带token
        String token=exchange.getRequest().getHeaders().getFirst("token").toString();

        //进行非空判断
        if (StringUtils.isEmpty(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            // 响应已经完成，提前响应数据给客户端
            Mono<Void> mono = exchange.getResponse().setComplete();
            return mono;
        }


        //此时就需要校验令牌是否正确
        ResultVO resultVO=iUserService.verify(token);
        if (resultVO.getCode() == 500) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            // 响应已经完成，提前响应数据给客户端
            Mono<Void> mono = exchange.getResponse().setComplete();
            return mono;
        }


        return chain.filter(exchange);
    }


    // 标识当前过滤器的优先级，返回的数字越小，优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
